/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.job.snailjob;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.isfd.constant.enums.IsfdMeshOp2BoStatusEnum;
import com.comac.ins.isfd.domain.IsfdDatabaseMongoQuery;
import com.comac.ins.isfd.domain.bo.IsfdMeshOp2InfoBo;
import com.comac.ins.isfd.service.IIsfdDatabaseMongoService;
import com.comac.ins.isfd.service.IIsfdMeshOP2ParseService;
import com.comac.ins.isfd.service.impl.IsfdMeshOp2ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 数据源数据集成任务调度执行器
 */
@Slf4j
@Component
@JobExecutor(name = "isfdOp2ParseJobExecutor")
public class IsfdOp2ParseJobExecutor {
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IsfdMeshOp2ServiceImpl isfdMeshOp2Service;

    @Autowired
    private IIsfdMeshOP2ParseService isfdMeshOP2ParseService;

    @Autowired
    private IIsfdDatabaseMongoService isfdDatabaseMongoService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        Date nowTime = new Date();
        // 查询数据
        String collectionName = isfdMeshOp2Service.getMeshModelTableName();
        IsfdDatabaseMongoQuery mongoQuery = new IsfdDatabaseMongoQuery();
        IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition queryCondition = new IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition();
        queryCondition.setFieldName("status");
        queryCondition.setOperator("eq");
        queryCondition.setValue(IsfdMeshOp2BoStatusEnum.INITIAL.getValue().toString());
        queryCondition.setValueNumberCheck(Boolean.TRUE);
        mongoQuery.setConditions(List.of(queryCondition));
        List<Document> results = isfdDatabaseMongoService.findAll(collectionName, mongoQuery);
        if (CollectionUtils.isEmpty(results)) {
            return ExecuteResult.success("所有文件都已结构化.任务调度执行完成！");
        }

        // 过滤重复uploadId
        List<Document> newResults =new ArrayList<>();
        Set<String> uploadIdSet = new HashSet<>();
        for (Document document : results) {
            String uploadId = (String) document.get("uploadId");
            if (!uploadIdSet.contains(uploadId)) {
                uploadIdSet.add(uploadId);
                newResults.add(document);
            }
        }

        //一个线程一个任务
        for (Document result : newResults) {
            String objectId = (String) result.get("_id");
            String uploadId = (String) result.get("uploadId");
            String fileHash = (String) result.get("fileHash");
            String filePath = (String) result.get("fileUrl");
            Integer status = (Integer) result.get("status");

            if (StringUtils.isBlank(objectId) ||
                StringUtils.isBlank(fileHash) ||
                StringUtils.isBlank(filePath) ||
                status == null) {
                return ExecuteResult.failure("结果数据存在问题，任务调度失败！");
            }


            IsfdMeshOp2InfoBo infoBo = new IsfdMeshOp2InfoBo();
            infoBo.setObjectId(objectId);
            infoBo.setUploadId(uploadId);
            infoBo.setFilePath(filePath);
            infoBo.setFileHash(fileHash);

            // 更新记录
            if (isfdMeshOP2ParseService.OP2ParseInfoExists(infoBo)) {
                continue;
            }
            isfdMeshOP2ParseService.updateStatusByUploadId(uploadId, IsfdMeshOp2BoStatusEnum.STRUCTURING, null, null, null);

            threadPoolTaskExecutor.execute(() -> {
                try {
                    isfdMeshOP2ParseService.parseAndSaveResultByType(infoBo);
                } catch (Exception e) {
                    log.error("结果数据结构化失败：" + e.getMessage(), e);
                    throw new BaseException("结果数据结构化失败：" + e.getMessage());
                }
            });
        }
        return ExecuteResult.success("结构化开始，任务调度执行完成！");
    }
}
